// pages/myTimeTable/myTimeTable.js
//获取应用实例
const app = getApp()
Date.prototype.Format = function(fmt) { //需要JS格式化时间，后期做的时候方便使用   
  var o = {
    "M+": this.getMonth() + 1, //月份   
    "d+": this.getDate(), //日   
    "h+": this.getHours(), //小时   
    "m+": this.getMinutes(), //分   
    "s+": this.getSeconds(), //秒   
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
    "S": this.getMilliseconds() //毫秒   
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
};
Page({

  /**
   * 页面的初始数据
   */
  data: {
    curDate: {},
    curWeekDate: [],
    weeksCount: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52],
    weekDay: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
    activeDay: 0,
    colorArr: ["#85B8CF", "#90C652", "#D8AA5A", "#FC9F9D", "#0A9A84", "#61BC69", "#12AEF3", "#E29AAD"],
    weekDateArr: [],
    modalDetail: false,
    courseList: [],
    weekCourseData: [], 
    showModal: false,
    showModalDel: false,
    isAddCourse: false,
    curCourseData: {},
    index: null,
    yearIndex:"1",
    yearsData: [{ name: "2019-2020学年第一学期", arr: [2019, 2020, 1] }, { name: "2019-2020学年第二学期", arr: [2019, 2020, 2] }, { name: "2020-2021学年第一学期", arr: [2020, 2021, 1] }, { name: "2020-2021学年第二学期", arr: [2020, 2021, 2] }],
    selectClass: {
      index: null,
      data: null
    },
    delId: null,
    classData: [{
      id: 1,
      name: "计应1901"
    }, {
      id: 1,
      name: "计应1902"
    }],
    picker: [],
    allCourse: [], //所有课程
    selCourseIndex: null, //选中课程的索引
    role: false //当前页面访问角色
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getMDay();
    app.getAllClass((data) => {
      console.log(data)
      this.setData({
        classData: data
      })
    })
    this.getAllCourse();
    this.getAllTeachers();
    this.getCourseByClassAndWeek();
    console.log(options);
    this.setData({
      role: options.role == "admin" ? true : false
    })
  },
  // function
  weekGetDate(year, weeks) {
    var date = new Date(year, "0", "1");
    // 获取当前星期几,0:星期一
    var time = date.getTime();
    //当这一年的1月1日为周日时则本年有54周,否则没有54周,没有则去除第54周的提示
    var _week = date.getDay();

    if (_week != 0) { //一年53周情况
      if (weeks == 54) {
        alert('今年没有54周');
      }
      var cnt = 7 - _week; // 获取距离周末的天数
      cnt += 1; //加1表示以星期一为一周的第一天    // 将这个长整形时间加上第N周的时间偏移
      time += cnt * 24 * 3600000; //第2周开始时间
      var nextYear = new Date(parseInt(year, 10) + 1, "0", "1");
      var nextWeek = nextYear.getDay();
      var lastcnt = nextWeek == 0 ? 6 : nextWeek - 1; //获取最后一周开始时间到周末的天数
      if (weeks == 1) { //第1周特殊处理    // 为日期对象 date 重新设置成时间 time
        var start = date.Format("yyyy-MM-dd");
        date.setTime(time - 24 * 3600000);

        return [start, date];
      } else if (weeks == 53) { //第53周特殊处理
        //第53周开始时间
        var start = time + (weeks - 2) * 7 * 24 * 3600000;
        //第53周结束时间
        var end = time + (weeks - 2) * 7 * 24 * 3600000 + lastcnt * 24 * 3600000 - 24 * 3600000;
        date.setTime(start);
        var _start = date.Format("yyyy-MM-dd");
        date.setTime(end);
        var _end = date.Format("yyyy-MM-dd");
        return [_start, _end];
      } else {
        var start = time + (weeks - 2) * 7 * 24 * 3600000; //第n周开始时间
        var end = time + (weeks - 1) * 7 * 24 * 3600000 - 24 * 3600000; //第n周结束时间
        date.setTime(start);
        var _start = date.Format("yyyy-MM-dd");
        date.setTime(end);
        var _end = date.Format("yyyy-MM-dd");
        return [_start, _end];
      }
    } else { //一年54周情况
      var cnt = (_week == 0 && weeks == 1) ? 0 : 7 - _week; // 获取距离周末的天数

      cnt += 1; //加1表示以星期一为一周的第一天
      // 将这个长整形时间加上第N周的时间偏移
      time += 24 * 3600000; //第2周开始时间
      var nextYear = new Date(parseInt(year, 10) + 1, "0", "1");
      var nextWeek = nextYear.getDay();
      var lastcnt = (nextWeek == 0) ? 6 : nextWeek - 1; //获取最后一周开始时间到周末的天数

      if (weeks == 1) { //第1周特殊处理
        var start = date.Format("yyyy-MM-dd");
        date.setTime(time - 24 * 3600000);
        // alert(start + '--' + date);
        return [_start, date];
      } else if (weeks == 54) { //第54周特殊处理
        //第54周开始时间
        var start = time + (weeks - 2) * 7 * 24 * 3600000;
        //第53周结束时间
        var end = time + (weeks - 2) * 7 * 24 * 3600000 + lastcnt * 24 * 3600000 - 24 * 3600000;
        date.setTime(start);
        var _start = date.Format("yyyy-MM-dd");
        date.setTime(end);
        var _end = date.Format("yyyy-MM-dd");
        return [_start, _end];
      } else {
        var start = time + (weeks - 2) * 7 * 24 * 3600000; //第n周开始时间
        var end = time + (weeks - 1) * 7 * 24 * 3600000 - 24 * 3600000; //第n周结束时间
        date.setTime(start);
        var _start = date.Format("yyyy-MM-dd");
        date.setTime(end);
        var _end = date.Format("yyyy-MM-dd");
        return [_start, _end];
      }
    }
  },
  getAllTeachers() {
    wx.request({
      url: app.globalData.baseService + '/user/selAll',
      success: (res) => {
        console.log("拿到的sessionkey", res);
        if (res.data.errorCode == 0) {
          let teachers = res.data.data.filter(item => item.roleId == 2);
          this.setData({
            picker: teachers
          })
        } else {
          wx.showToast({
            title: res.data.errorMsg,
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail() {
        wx.showToast({
          title: "请求出错，请稍后重试！",
          icon: 'none',
          duration: 2500
        })
      }
    })
  },
  getAllCourse() {
    //获取所有课程
    wx.request({
      url: app.globalData.baseService + '/course/selAll',
      success: (res) => {
        console.log("拿到的sessionkey", res);
        if (res.data.errorCode == 0) {
          this.setData({
            allCourse: res.data.data
          })
        } else {
          wx.showToast({
            title: res.data.errorMsg,
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail() {
        wx.showToast({
          title: "请求出错，请稍后重试！",
          icon: 'none',
          duration: 2500
        })
      }
    })
  },
  getWeekNum(dateString) {
    var da = '';
    if (dateString == undefined) {
      var now = new Date();
      var now_m = now.getMonth() + 1;
      now_m = (now_m < 10) ? '0' + now_m : now_m;
      var now_d = now.getDate();
      now_d = (now_d < 10) ? '0' + now_d : now_d;
      da = now.getFullYear() + '-' + now_m + '-' + now_d;
      console.log('今天系统时间是:' + da);
    } else {
      da = dateString; //日期格式2015-12-30
    }
    var date1 = new Date(da.substring(0, 4), parseInt(da.substring(5, 7)) - 1, da.substring(8, 10)); //当前日期
    var date2 = new Date(da.substring(0, 4), 0, 1); //1月1号
    //获取1月1号星期（以周一为第一天，0周一~6周日）
    var dateWeekNum = date2.getDay() - 1;
    if (dateWeekNum < 0) {
      dateWeekNum = 6;
    }
    if (dateWeekNum < 4) {
      //前移日期
      date2.setDate(date2.getDate() - dateWeekNum);
    } else {
      //后移日期
      date2.setDate(date2.getDate() + 7 - dateWeekNum);
    }
    var d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000);
    if (d < 0) {
      var date3 = (date1.getFullYear() - 1) + "-12-31";
      return getYearWeek(date3);
    } else {
      //得到年数周数
      var week = Math.ceil((d + 1) / 7);
      return week;
    }
  },
  getMDay: function() {
    let d1 = new Date(),
      year = d1.getFullYear(),
      day = d1.getDay();
    let week = this.getWeekNum();
    day=day==0?6:day-1;
    this.setData({
      curDate: {
        week,
        year,
        day
      },
      activeDay: day
    })
    console.log(this.data.curDate)
  },

  toDeleteCourse(e) {
    // 删除排课
    this.setData({
      showModalDel: true,
      delId: e.currentTarget.dataset.delid
    })
  },
  toEditCourse(e) {
    //编辑用户信息
    console.log(e)
    let tempObj = JSON.parse(JSON.stringify(e.currentTarget.dataset.course));
    this.setData({
      showModal: true,
      isAddCourse: false,
      curCourseData: tempObj
    })
  },
  addCourse() {
    // 新增用户
    let choosedClass = this.data.selectClass.index
    if (!choosedClass && choosedClass != 0) {
      wx.showToast({
        title: "请先选择班级",
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    this.setData({
      showModal: true,
      isAddCourse: true,
      selCourseIndex: null,
      index: null
    })
  },
  yearChange(e){
    this.setData({
      "yearIndex": e.detail.value
    })
    this.getCourseByClassAndWeek();
  },
  classChange(e) {
    console.log(e.detail.value)
    this.setData({
      "selectClass.index": e.detail.value,
      "selectClass.data": this.data.classData[e.detail.value]
    })
    this.getCourseByClassAndWeek();
    console.log(this.data.classData[e.detail.value])
  },
  weekChange(e) {
    this.setData({
      "curDate.week": +e.detail.value + 1
    })

    this.getCourseByClassAndWeek();
    this.getCurWeekDay();
  },
  PickerChange(e) {
    console.log(e.detail.value)
    this.setData({
      index: e.detail.value,
      "curCourseData.teacherId": this.data.picker[e.detail.value].id
    })
  },
  selectCourse(e) {
    //选择课程
    this.setData({
      selCourseIndex: e.detail.value,
      "curCourseData.courseId": this.data.allCourse[e.detail.value].id
    })
  },
  getWeekthCourse(e) {
    this.setData({
      activeDay: e.currentTarget.dataset.index
    })
    this.getCourseByClassAndWeek();
  },
  getCourseByClassAndWeek() {
    //通过班级和周次查询课表
    let dataset = {
      clazzId: app.globalData.localuser.clazzId,
      startYear: this.data.yearsData[this.data.yearIndex].arr[0],
      endYear: this.data.yearsData[this.data.yearIndex].arr[1], 
      term: this.data.yearsData[this.data.yearIndex].arr[2],
      weeks: this.data.curDate.week
    }
    // weekth: this.data.curDate.week,week: this.data.activeDay == 0 ? 7 : this.data.activeDay
    wx.request({
      url: app.globalData.baseService + '/timetable/queryByConditon',
      data: dataset,
      success: (res) => {
        console.log("拿到的sessionkey", res.data);
        if (res.data.errorCode == 0) {
          this.setData({
            courseList: res.data.data||[]
          })
        } else {
          wx.showToast({
            title: res.data.errorMsg,
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail() {
        wx.showToast({
          title: "请求出错，请稍后重试！",
          icon: 'none',
          duration: 2500
        })
      }
    })
  },
  hideModalDetail() {
    this.setData({
      modalDetail: false,
      curCourseData: {}
    })
  },
  hideModal() {
    this.setData({
      showModal: false,
      curCourseData: {}
    })
  },
  hideModalDel() {
    this.setData({
      showModalDel: false
    })
  },
  getInputVal(e) {
    //获取失焦后输入框的值
    let name = e.currentTarget.dataset.name;
    let nameMap = {}
    nameMap[name] = e.detail && e.detail.value
    this.setData(nameMap)
  },
  confirmEnter() {
    //确认编辑    
    // let yearArr = this.data.curCourseData.startEndYear.split("-");
    let dataset = {
      ...this.data.curCourseData,
      clazzId: this.data.classData[this.data.selectClass.index].id,
      weeks: this.data.curDate.week,
      week: this.data.activeDay == 0 ? 7 : this.data.activeDay,
      startYear: this.data.yearsData[this.data.yearIndex].arr[0],
      endYear: this.data.yearsData[this.data.yearIndex].arr[1],
      term: this.data.yearsData[this.data.yearIndex].arr[2],
    }
    // Object.assign(dataset, tempObj, this.data.curCourseData)
    console.log(dataset);
    wx.request({
      url: app.globalData.baseService + '/timetable/add',
      method: "post",
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      data: dataset,
      success: (res) => {
        console.log("拿到的sessionkey", res);
        if (res.data.errorCode == 0) {
          this.getCourseByClassAndWeek();
        } else {
          wx.showToast({
            title: res.data.errorMsg,
            icon: 'none',
            duration: 2000
          })
        }
        this.hideModal();
      },
      fail() {
        wx.showToast({
          title: "请求出错，请稍后重试！",
          icon: 'none',
          duration: 2500
        })
      }
    })
  },
  confirmDel() {
    //确认删除
    console.log(this.data.delId)
    wx.request({
      url: app.globalData.baseService + '/timetable/delTimetable',
      method: "post",
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      data: {
        id: this.data.delId
      },
      success: (res) => {
        console.log("拿到的sessionkey", res);
        if (res.data.errorCode == 0) {
          this.getCourseByClassAndWeek();
        } else {
          wx.showToast({
            title: res.data.errorMsg,
            icon: 'none',
            duration: 2000
          })
        }
        this.hideModalDel();
      },
      fail() {
        wx.showToast({
          title: "请求出错，请稍后重试！",
          icon: 'none',
          duration: 2500
        })
      }
    })
  },
  showMore(e) {
    let item = e.currentTarget.dataset.item;
    console.log(item)
    this.setData({
      modalDetail: true,
      curCourseData: item
    })
  },
  // 获取当前周七天日期
  getCurWeekDay() {
    let dateArr = this.weekGetDate(this.data.curDate.year, this.data.curDate.week);
    let res = [];
    for (let i = 0; i < 7; i++) {
      let tempDate = new Date(dateArr[0]);
      tempDate.setDate(tempDate.getDate() + i);
      let obj = {
        year: tempDate.getFullYear(),
        month: tempDate.getMonth() + 1,
        day: tempDate.getDate() > 9 ? tempDate.getDate() : "0" + tempDate.getDate()
      };
      res.push(obj);
    }
    this.setData({
      curWeekDate: res
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log(this.weekGetDate(2020, this.data.curDate.week))
    this.getCurWeekDay();
    // this.setData({
    //   weekDateArr: 
    // })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})